﻿Imports System.Web.UI
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Configuration
Imports System.Net.Mail

Partial Public Class Wfrm_ConsultarSolicitud
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'session("usuario")
        If Not Page.IsPostBack Then
            'txtNsolicitud.Attributes.Add("onkeypress", "javascript:return ValidNum(event);")
            'Session("usu") = Session("usuario")
            ViewState("usu") = Session("usuario")
            carga_bodega()
            FK_EMPRESA()
            CreaDatatable()

            txtSolicitud.ReadOnly = True
            txtSolicitud.UpdateAfterCallBack = True
            cmbBodega.Enabled = False
            cmbBodega.UpdateAfterCallBack = True
            Panel3.Visible = False
            Panel3.UpdateAfterCallBack = True

            Carga_Datos_Usuario()


        End If
        'Anthem.Manager.Register(Me)
        'Anthem.Manager.AddScriptForClientSideEval("$(document).ready(function () {$('#DataGrid1').initTable( {perPages:[5,12,15,50,'ALL']} ).controlTable();});")


    End Sub
    Sub Carga_Datos_Usuario()
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_Get_INFO_FORM"
        rp.AddParametro(ViewState("usu"))
        exec.ExecuteDataTable(rp)

        If rp.TieneDatos Then
            lbl_clinica.Text = rp.DtTable.Rows(0).Item("tNombreFantasia").ToString.Trim
            lbl_usuario.Text = rp.DtTable.Rows(0).Item("Tnombre").ToString.Trim
            lbl_fecha.Text = Now

            lbl_clinica.UpdateAfterCallBack = True
            lbl_usuario.UpdateAfterCallBack = True
            lbl_fecha.UpdateAfterCallBack = True

        End If

    End Sub
    Sub CreaDatatable() 'JQ
        Dim Dt2 As New DataTable
        Dt2.Columns.Add("")
        Dt2.Columns.Add("nCodigo_PKI")
        Dt2.Columns.Add("Producto")
        Dt2.Columns.Add("tNombre")
        Dt2.Columns.Add("CANT_SOLICITADA")
        ViewState("DT") = Dt2
    End Sub
    Sub FK_EMPRESA()
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence

        rp.StoredProcedure = ("SP_OC_GET_FK_EMPRESA")
        rp.AddParametro(ViewState("usu"))
        exec.ExecuteDataTable(rp)

        If rp.TieneDatos Then
            ViewState("FK_EMPRESA") = rp.DtTable.Rows(0).Item(0).ToString
        End If
        If rp.Errores Then
            'erro
        Else
            'ok
        End If

    End Sub
    Sub carga_bodega()
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.ClearParametro()
        rp.TieneDatos = False
        rp.StoredProcedure = ("SP_OC_CARGA_BODEGA_ALL")
        rp.AddParametro(ViewState("usu")) 'ViewState("usu")
        exec.ExecuteDataTable(rp)

        If rp.TieneDatos Then
            cmbBodega.DataTextField = "DESCRIPCION"
            cmbBodega.DataValueField = "ID_BODEGA"
            cmbBodega.DataSource = rp.DtTable
            cmbBodega.DataBind()
            cmbBodega.UpdateAfterCallBack = True
        End If

        rp.ClearParametro()
        rp.TieneDatos = False

        rp.StoredProcedure = "SP_OC_CARGA_ESTADO"
        exec.ExecuteDataTable(rp)

        If rp.TieneDatos Then
            cmb_estado_solicitud.DataTextField = "s_texto"
            cmb_estado_solicitud.DataValueField = "id_concepto"
            cmb_estado_solicitud.DataSource = rp.DtTable
            cmb_estado_solicitud.DataBind()

            cmb_estado_solicitud.SelectedValue = "-1"
            cmb_estado_solicitud.UpdateAfterCallBack = True

        End If
    End Sub


    Private Function SumarProducto(ByVal codProducto As String) As Decimal 'JQ
        Dim i As Integer
        For i = 0 To DataGrid2.Items.Count - 1
            If codProducto = DataGrid2.Items(i).Cells(1).Text Then
                Return DirectCast(DirectCast(DataGrid2.Items(i).Cells(4).FindControl("Label5"), System.Web.UI.Control), Label).Text

            End If
        Next
        Return 0
    End Function

    Sub AgregaProducto(ByVal fk_solicitud As String, ByVal fk_producto As String, ByVal Cant_sol As Decimal) 'JQ

        Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence

        rp.StoredProcedure = "SP_OC_ADD_SOLICITUD_PRODUCTO"

        rp.AddParametro(fk_solicitud)
        rp.AddParametro(fk_producto)
        rp.AddParametro(Cant_sol)
        rp.AddParametro(ViewState("usu"))

        exec.ExecuteNonQuery(rp)
        exec.Commit()

        If rp.Errores Then

        End If
    End Sub
    Sub ActualizaProducto(ByVal fk_solicitud As String, ByVal fk_producto As String, ByVal Cant_sol As Decimal) 'JQ

        Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence

        rp.StoredProcedure = "SP_OC_UPDATE_SOLICITUD_PRODUCTO"

        rp.AddParametro(fk_solicitud)
        rp.AddParametro(fk_producto)
        rp.AddParametro(Cant_sol)
        rp.AddParametro(ViewState("usu"))

        exec.ExecuteNonQuery(rp)
        exec.Commit()

        If rp.Errores Then

        End If
    End Sub

    Sub GetProductosSolicitud()  'JQ   
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_GET_SOLICITUD_PRODUCTO"
        rp.AddParametro(txtSolicitud.Text)
        exec.ExecuteDataTable(rp)

        'ViewState("DT") = rp.DtTable
        If rp.TieneDatos Then
            ViewState("datos") = rp.DtTable.Rows(0).Item(4).ToString
            DataGrid2.DataSource = rp.DtTable
            DataGrid2.DataBind()
            DataGrid2.Enabled = False
            DataGrid2.UpdateAfterCallBack = True
        Else
            DataGrid2.DataSource = Nothing
            DataGrid2.DataBind()
            DataGrid2.Enabled = False
            DataGrid2.UpdateAfterCallBack = True

        End If

        'rp.ClearParametro()
        'rp.TieneDatos = False
        'rp.StoredProcedure = "SP_OC_GET_SOLICITUD_PRODUCTO_OC"
        'rp.AddParametro(txtSolicitud.Text)
        'exec.ExecuteDataTable(rp)

        'If rp.TieneDatos Then
        '    DataGrid4.DataSource = rp.DtTable
        '    DataGrid4.DataBind()
        '    DataGrid4.Enabled = False
        '    DataGrid4.UpdateAfterCallBack = True
        'Else
        '    DataGrid4.DataSource = Nothing
        '    DataGrid4.DataBind()
        '    DataGrid4.Enabled = False
        '    DataGrid4.UpdateAfterCallBack = True
        'End If
        'If rp.Errores Then

        'End If
    End Sub
    Protected Sub DataGrid2_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DataGrid2.SelectedIndexChanged
        Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        If Val(txtSolicitud.Text) = 0 Then
            Dim i As Integer
            For i = 0 To ViewState("DT").Rows.Count - 1
                If ViewState("DT").Rows(i).Item(1) = DataGrid2.SelectedItem.Cells(1).Text Then  'cmbProducto.SelectedValue Then DU
                    ViewState("DT").Rows(i).Delete()
                    Exit For
                End If
            Next

            DataGrid2.DataSource = ViewState("DT")
            DataGrid2.DataBind()
            DataGrid2.UpdateAfterCallBack = True

        Else
            'se quita fila directamente de la tabla

            For i = 0 To ViewState("DT").Rows.Count - 1
                If ViewState("DT").Rows(i).Item(0) = DataGrid2.SelectedItem.Cells(1).Text Then  'cmbProducto.SelectedValue Then DU
                    ViewState("DT").Rows(i).Delete()
                    Exit For
                End If
            Next

            'hacer sp pa eliminar de la tabla  --- parecido al update 

            rp.StoredProcedure = "SP_OC_DELETE_PRODUCTO"
            rp.AddParametro(DataGrid2.SelectedItem.Cells(1).Text)
            rp.AddParametro(DirectCast(DataGrid1.SelectedItem.Cells(0).Controls(1), Anthem.LinkButton).Text)
            'DataGrid1.SelectedItem.Cells(0).Text)
            exec.ExecuteNonQuery(rp)
            exec.Commit()
            If rp.Errores Then

            End If

            'Cargar grilla
            GetProductosSolicitud()

        End If


    End Sub

    Protected Sub DataGrid1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DataGrid1.SelectedIndexChanged

        txtSolicitud.Text = DirectCast(DataGrid1.SelectedItem.Cells(0).Controls(1), Anthem.LinkButton).Text
        txtSolicitud.UpdateAfterCallBack = True
        GetProductosSolicitud()

        cmbBodega.SelectedValue = DataGrid1.SelectedItem.Cells(3).Text
        cmbBodega.UpdateAfterCallBack = True
        cmbBodega.Enabled = False
        cmbBodega.UpdateAfterCallBack = True

        pnl_productos.Visible = True
        Panel2.Visible = True

        Img_Imprimir.Visible = True
        Img_Imprimir.UpdateAfterCallBack = True

        lblSolicitud0.Visible = True

        lblSolicitud0.UpdateAfterCallBack = True
        pnl_productos.UpdateAfterCallBack = True
        Panel2.UpdateAfterCallBack = True

        lbl_nro_solicitud.Text = txtSolicitud.Text
        lbl_nro_solicitud.UpdateAfterCallBack = True

        Try
            lbl_nro_productos.Text = DataGrid2.Items.Count
            lbl_nro_productos.UpdateAfterCallBack = True
        Catch ex As Exception

        End Try

        'CREADA()
        'ENVIADA()
        'ACEPTADA

        'btnAnular.Visible = False
        'If DataGrid1.SelectedItem.Cells(4).Text = 0 Or DataGrid1.SelectedItem.Cells(4).Text = 1 Or DataGrid1.SelectedItem.Cells(4).Text = 2 Then
        '    btnAnular.Visible = True
        'End If
        'btnAnular.UpdateAfterCallBack = True


        'If ViewState("datos") = "1" Then

        '    txtCantidad.ReadOnly = True
        '    txtCantidad.UpdateAfterCallBack = True
        '    ViewState("datos") = Nothing
        '    DataGrid2.Enabled = False
        '    DataGrid2.UpdateAfterCallBack = True
        '    cmbBodega.Enabled = False
        '    cmbProducto.Enabled = False
        '    cmbBodega.UpdateAfterCallBack = True
        '    cmbProducto.UpdateAfterCallBack = True
        'Else

        '    txtCantidad.ReadOnly = False
        '    txtCantidad.UpdateAfterCallBack = True
        '    ViewState("datos") = Nothing
        '    DataGrid2.Enabled = True
        '    DataGrid2.UpdateAfterCallBack = True
        '    cmbBodega.Enabled = True
        '    cmbProducto.Enabled = True
        '    cmbBodega.UpdateAfterCallBack = True
        '    cmbProducto.UpdateAfterCallBack = True
        'End If
    End Sub

    Protected Sub btnBuscaSol_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBuscaSol.Click
        BuscarSol()
    End Sub

    Sub BuscarSol()
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence

        If txtStartDate.Text.Trim = "" And txtEndDate.Text.Trim = "" And txtNsolicitud.Text.Trim = "" And txtNsolicitud0.Text.Trim = "" Then
            Mensaje("Falta Ingresar filtro de busqueda")
            Exit Sub
        End If

        Dim fecha_ini As String
        Dim fecha_fin As String
        Dim nroi As String = Val(txtNsolicitud.Text.Trim)
        Dim nrot As String = Val(txtNsolicitud0.Text.Trim)
        Dim Estado As String = cmb_estado_solicitud.SelectedValue

        If cmb_estado_solicitud.SelectedValue = "-1" Then
            Estado = Nothing
        End If
        If Val(txtNsolicitud.Text.Trim) = 0 Then
            nroi = Nothing
        End If

        If Val(txtNsolicitud0.Text.Trim) = 0 Then
            nrot = Nothing
        End If

        If IsDate(txtStartDate.Text) Then
            fecha_ini = Convert.ToDateTime(txtStartDate.Text).ToString("yyyyMMdd")
        Else
            fecha_ini = Nothing
        End If
        If IsDate(txtEndDate.Text) Then
            fecha_fin = Convert.ToDateTime(txtEndDate.Text).ToString("yyyyMMdd")
        Else
            fecha_fin = Nothing
        End If


        rp.StoredProcedure = "SP_OC_GET_SOLICITUD"
        rp.AddParametro(nroi)
        rp.AddParametro(nrot)
        rp.AddParametro(fecha_ini)
        rp.AddParametro(fecha_fin)
        rp.AddParametro(Estado)
        rp.AddParametro(ViewState("usu"))

        exec.ExecuteDataTable(rp)


        If rp.TieneDatos Then
            Panel3.Visible = True
            Panel3.UpdateAfterCallBack = True
            DataGrid1.DataSource = rp.DtTable
            DataGrid1.DataBind()
            DataGrid1.UpdateAfterCallBack = True

            'For i = 0 To DataGrid1.Items.Count - 1
            '    DataGrid1.Items(i).Cells(2).Text = DataGrid1.Items(i).Cells(2).Text.Substring(6, 2) & "-" & DataGrid1.Items(i).Cells(2).Text.Substring(4, 2) & "-" & DataGrid1.Items(i).Cells(2).Text.Substring(0, 4)  'Convert.ToDateTime(DataGrid1.Items(i).Cells(1).Text).ToString("dd-MM-yyyy")
            '    DataGrid1.UpdateAfterCallBack = True
            'Next
        Else
            DataGrid1.DataSource = Nothing
            DataGrid1.DataBind()
            DataGrid1.UpdateAfterCallBack = True
            Mensaje("No se encontraron registros")
        End If
        If rp.Errores Then
            Mensaje(rp.MensajeError)             
        End If

        Panel2.Visible = True

    End Sub
    Sub Mensaje(ByVal mensaje As String)
        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & mensaje & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & mensaje & "')</script>")
        End If
    End Sub
    Sub Mensaje(ByVal tbl As String, ByVal codigo As String)

        Dim Mensaje As String = FuncionesGlobal.GetMensaje(tbl, codigo)

        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & Mensaje & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & Mensaje & "')</script>")
        End If


    End Sub
    Sub Mensaje0(ByVal tbl As String, ByVal codigo As String)
        Dim Mensaje As String = FuncionesGlobal.GetMensaje(tbl, codigo)

        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & Mensaje & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & Mensaje & "')</script>")
        End If

    End Sub


    Protected Sub Img_Imprimir_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Img_Imprimir.Click
        Dim rp As New Rpt_Solicitud
        Dim _CRConnectionInfo As ConnectionInfo

        _CRConnectionInfo = New ConnectionInfo()
        _CRConnectionInfo.ServerName = ConfigurationManager.AppSettings("cnn_server") '"application.dyndns-web.com"
        _CRConnectionInfo.DatabaseName = ConfigurationManager.AppSettings("cnn_database") '"comprasFarm"
        _CRConnectionInfo.UserID = ConfigurationManager.AppSettings("cnn_userid") '"lilas"
        _CRConnectionInfo.Password = ConfigurationManager.AppSettings("cnn_password") '"lilas"

        Dim tables As Tables
        tables = rp.Database.Tables
        For i = 0 To tables.Count - 1
            Dim tableLogonInfo As TableLogOnInfo = tables(i).LogOnInfo
            tableLogonInfo.ConnectionInfo = _CRConnectionInfo
            tables(i).ApplyLogOnInfo(tableLogonInfo)
        Next
        rp.SetParameterValue(1, lbl_nro_solicitud.Text)
        rp.SetParameterValue(0, ViewState("usu"))
        'rp.ParameterFields = ViewState("usuario")

        'Dim crParameterFieldDefinitions As ParameterFieldDefinitions
        'Dim crParameterFieldDefinition As ParameterFieldDefinition
        'Dim crParameterValues As New ParameterValues
        'Dim crParameterDiscreteValue As New ParameterDiscreteValue

        'crParameterDiscreteValue.Value = ViewState("usuario")
        'crParameterFieldDefinitions = rp.DataDefinition.ParameterFields()
        'crParameterFieldDefinition = crParameterFieldDefinitions.Item("usuario")
        'crParameterValues = crParameterFieldDefinition.CurrentValues

        'crParameterValues.Clear()
        'crParameterValues.Add(crParameterDiscreteValue)
        'crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)

        rp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Page.Response, True, "Solicitud_Nro_" & lbl_nro_solicitud.Text & ".pdf")

    End Sub

    Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand
        '// Alternate sorting between ascending and descending.
        BuscarSol()
       
        Dim Vista As DataView = DirectCast(DataGrid1.DataSource, DataTable).DefaultView
        If ViewState("orden") = Nothing Then
            ViewState("orden") = e.SortExpression & " DESC"
        Else
            If ViewState("orden") <> e.SortExpression Then
                ViewState("orden") = e.SortExpression
            Else
                ViewState("orden") = e.SortExpression & " DESC"
            End If
        End If        
        DirectCast(DataGrid1.DataSource, DataTable).DefaultView.Sort = ViewState("orden")
        DataGrid1.DataBind()
        DataGrid1.UpdateAfterCallBack = True

    End Sub

End Class
